package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TrafficPageViewBean;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.DorisUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/28 08:52
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow_Doris extends BaseApp {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow_Doris().init(
            40002,
            2,
            "Dws_02_DwsTrafficVcChArIsNewPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 把日志解析成 pojo 类型
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
    
        // 3. 写出到 clickhouse
        writeToDoris(resultStream);
    }
    
    private void writeToDoris(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream
            .map(bean -> {
                SerializeConfig config = new SerializeConfig();
                config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                return JSON.toJSONString(bean, config);
            })
            .sinkTo(DorisUtil.getDorisSink("gmall.dws_traffic_vc_ch_ar_is_new_page_view_window"));
    
    
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
       return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))  // 解决数据倾斜导致的水印不更新问题
            )
            .keyBy(bean -> bean.getVc() + "_" + bean.getCh() + "_" + bean.getAr() + "_" + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean value1,
                                                      TrafficPageViewBean value2) throws Exception {
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
    
                        return value1;
                    }
                },
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,  // key
                                        Context ctx,  // 上下文对象
                                        // 有且仅有一个
                                        Iterable<TrafficPageViewBean> elements,  // 只存储了一个元素: 前面 reduce 计算的最终结果
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setCur_date(DateFormatUtil.toPartitionDate(ctx.window().getStart()));
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
                
                private ValueState<String> lastVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitDate", String.class));
                }
                
                @Override
                public TrafficPageViewBean map(JSONObject obj) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    JSONObject page = obj.getJSONObject("page");
                    Long durSum = page.getLong("during_time");
                    
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    Long pvCt = 1L;  //
                    
                    Long uvCt = 0L;  // 如果是当天第一条则置为 1
                    String lastVisitDate = lastVisitDateState.value();
                    if (!today.equals(lastVisitDate)) {
                        uvCt = 1L;
                        lastVisitDateState.update(today);
                    }
                    
                    Long svCt = 0L;  //
                    String lastPageId = page.getString("last_page_id");
                    // 是一个新的会话
                    if (lastPageId == null || lastPageId.length() == 0) {
                        svCt = 1L;
                    }
                    
                    return new TrafficPageViewBean("", "",
                                                   vc, ch, ar, isNew, "",
                                                   uvCt, svCt, pvCt, durSum,
                                                   ts
                    );
                }
            });
    }
}
/*
流量域版本-渠道-地区-访客类别粒度页面浏览各窗口汇总表

页面浏览数 pv  page view
独立访客数 uv  unique visitor
会话数    sv
浏览总时长

------
数据源:
    dwd 层页面日志
    
 一条日志:
    pv 贡献  1
    dur_sim
        "during_time" 聚合
    uv 按照mid
        这个用户当天的第一条访问日志贡献 1 其他日志贡献 1
        需要状态记录这个用户最后一次访问日期
            当用户第一条数据来的时候,状态为 null, 今天的第一条. 把今天存入到状态中
            再有数据过来,判断这条数据的日期与状态是否一致, 如果一致就是当天
            如果不一致,表示到了第二条, 贡献 1
            
    sv
        思路 1: 如果有 sid, 则可以对 sid 分组, 然后这个 sid 的第一条日志贡献 1, 其他的 0
        思路 2: 如果没有 sid, 找那些 last_page_id is null 的页面  选择第二种
        
----------
版本-渠道-地区-访客类   pv  uv       sv  dur_sum
xxxx                  1  1/0    1/0   2000
xxxx                  1  1/0    1/0   2000
...

keyBy 开窗 聚合

写出到 clickhouse


----

创建处理函数:
    简单
        sum 增量
        max min 增量
        maxBy minBy 增量

    复杂
        reduce   增量
            当输入和输出类型一样
        
        aggregate 增量
            当输入和输出类型可以不一样
                累加器
        
        process  全量
        
        
 */